package com.paipai.scheduled;

import com.paipai.dao.RoundMapper;
import com.paipai.entity.Round;
import com.paipai.utils.JsonUtils;
import javafx.util.Builder;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class ScheduledTask {
    @Autowired
    RoundMapper roundMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0 0 0 * * ?")
    public void startRound()  {
        System.out.println("定时任务执行");
        //设置每天凌晨12点从数据库获得当天需要拍卖的拍卖场数据
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + 24 * 3600 * 1000);
        List<Round> rounds = roundMapper.selectOneDayRounds(startDate, endDate);
        System.out.println(JsonUtils.toJson(rounds));
        //将符合该时间段的拍卖场放入rabbitmq  并设置消息过期时间
        for (Round round : rounds) {
            long expiration=round.getStarttime().getTime()-new Date().getTime();
            //定义message对象
            Message message= MessageBuilder.withBody(JsonUtils.toJson(round).getBytes()).setExpiration(String.valueOf(expiration)).build();
            //定义CorrelationData对象以及消息属性。不然comfirm方法无论失败还是成功，CorrelationData参数永远是null
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            correlationData.setReturnedMessage(new Message(JsonUtils.toJson(round).getBytes(),new MessageProperties()));
            //发送消息
            rabbitTemplate.convertAndSend("scheduledStartRoundExchange","roukey2",message,correlationData);
            System.out.println("当前时间："+new Date().toString()+"编号："+round.getId()+"入队"+"过期时间："+expiration/(1000.0*60)+"分钟");
        }
    }
}
